package com.yonyou.pmclouds.plan.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.entity.TreeVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.basecom.util.TreeVOUtil;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.plan.entity.*;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleItemQueryService;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleProgressHistoryQueryService;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleQueryService;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleService;
import com.yonyou.pmclouds.plan.util.ScheduleUtil;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workflow.aspect.PMApprove;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/mobile/schedule","/schedule"})
public class ScheduleMobileController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IScheduleService scheduleService;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IScheduleQueryService scheduleQueryService;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IScheduleProgressHistoryQueryService scheduleProgressHistoryQueryService;

    @Autowired
    private UserInfoQuery userInfoQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IScheduleItemQueryService scheduleItemQueryService;

    private static final String HAS_PLAN = "hasPlan";
    private static final String MY_PLAN = "myPlan";
    private static final String ALL_PLAN = "allPlan";

    @RequestMapping("/updateProgress")
    public ScheduleReportVO updateProgress(@RequestBody ScheduleReportVO reportVO) throws BusinessException {
        return scheduleService.updateProgress(reportVO);
    }

    @RequestMapping("/addDefault")
    @PMApprove(trigger = "save")
    public ScheduleVO addDefault(@RequestBody ScheduleVO scheduleVO) throws BusinessException{
        return scheduleService.addDefault(scheduleVO);
    }

    @GetMapping("/getScheduleData")
    public Map getScheduleData(@RequestParam("projectId") String projectId) throws BusinessException {

        HashMap<String, Object> data = new HashMap<>();
        List<ScheduleVO> scheduleVOS = scheduleQueryService.queryByPkProject(projectId);

        if (scheduleVOS == null || scheduleVOS.isEmpty()) {
            //当前项目没有计划
            data.put(HAS_PLAN,false);
            data.put(MY_PLAN,null);
            data.put(ALL_PLAN,null);
            return data;
        }

        List<ScheduleVO> newScheduleVOList = new ArrayList<>();
        for(ScheduleVO scheduleVO : scheduleVOS){
            if(scheduleVO.getBillstatus() == BillStatusConst.COMMON_APPROVED_STATUS){
                newScheduleVOList.add(scheduleVO);
            }
        }

        if(newScheduleVOList.size() <= 0){
            //当前项目没有计划
            data.put(HAS_PLAN,false);
            data.put(MY_PLAN,null);
            data.put(ALL_PLAN,null);
            return data;
        }
        ProjectVO projectVO = projectSimpleQuery.queryProject(projectId);
        String userId = RuntimeEnvironment.getLoginUserId();

        ArrayList<ScheduleVO> lastNodeList = new ArrayList<>();

        ArrayList<ScheduleVO> TreeVOList = new ArrayList<>();

        for (ScheduleVO scheduleVO : newScheduleVOList) {
            //构建树形结构
            List<TreeVO> treeVOS = TreeVOUtil.buildTree(scheduleVO.getScheduleItemVOS());

            //计算编码
            ScheduleUtil.genCodeOfTree(null,treeVOS.toArray(new ScheduleItemVO[0]));

            //设置noManagerFlag
            TreeVOUtil.setNoManagerFlag(null,treeVOS);

            //过滤我的任务
            List<TreeVO> lastNodeVOByManager = TreeVOUtil.getLastNodeVOByManager(userId, treeVOS);
            //防止下边赋值覆盖  这里copy一个对象
            if (lastNodeVOByManager != null && !lastNodeVOByManager.isEmpty()) {
                ScheduleVO tempScheduleVO = new ScheduleVO();
                BeanUtils.copyProperties(scheduleVO, tempScheduleVO);
                tempScheduleVO.setScheduleItemVOS(lastNodeVOByManager.toArray(new ScheduleItemVO[0]));
                lastNodeList.add(tempScheduleVO);
            }

            //过滤全部可查看任务
            if(!StringUtils.isEmpty(projectVO.getManager()) && userId.equals(projectVO.getManager())) {
                TreeVOList.add(scheduleVO); //不过滤
                continue;
            }
            List<TreeVO> treeVOByManager = TreeVOUtil.getTreeVOByManager(userId, treeVOS);
            if (treeVOByManager != null && !treeVOByManager.isEmpty()) {
                scheduleVO.setScheduleItemVOS(treeVOByManager.toArray(new ScheduleItemVO[0]));
                TreeVOList.add(scheduleVO);
            }
        }

        data.put(HAS_PLAN,true);
        data.put(MY_PLAN,lastNodeList);
        data.put(ALL_PLAN, TreeVOList);

        return data;

    }

    @GetMapping("/progressHistory")
    public PlanProgressHistoryVO[] queryProgressHisByPlan(@RequestParam("pkOriginal") String pkOriginal) throws BusinessException {
        PlanProgressHistoryVO[] his = scheduleProgressHistoryQueryService.queryProgressHisByPlan(pkOriginal);
        if (!ArrayUtils.isEmpty(his)) {
            userInfoQuery.tranUserInfoField(his, new String[]{CommonFieldConst.CREATOR}, new String[]{CommonFieldConst.CREATOR_NAME});
        }
        return his;
    }

    @GetMapping("/queryByPkPlan")
    public ScheduleReportVO queryByPkPlan(@RequestParam("pkScheduleItem") String pkScheduleItem) throws BusinessException {

        /**
         *  1. 通过pkPlan 查询ScheduleItemVO
         *  2. 在通过pkPlan查询反馈记录信息
         *  3. 在通过pkPlan 查询指标记录信息
         */
        return scheduleItemQueryService.queryByPkItem(pkScheduleItem);
    }


    /**
     *  返回关联单据的任务项  （目前用于阶段验收）
     * @return
     * @throws BusinessException
     */
    @GetMapping("/getCheckPlan")
    public ScheduleItemVO[] getCheckPlan(String pkProject,String billType) throws BusinessException{

        ScheduleItemVO[] scheduleItemVOS = scheduleItemQueryService.queryByProjectAndRelatedBillType(pkProject, billType);

        //做数据过滤 只能参照进度小于 100的
        ArrayList<ScheduleItemVO> result = new ArrayList<>();
        for (ScheduleItemVO scheduleItemVO : scheduleItemVOS) {
            //scheduleItemVO
            if (scheduleItemVO.getProgressVO() == null || scheduleItemVO.getProgressVO().getProgress() < 100) {
               result.add(scheduleItemVO);
            }
        }

        return result.toArray(new ScheduleItemVO[0]);
    }
}
